/**
 * Copyright 2023 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "pipeline/jit/pi/graph_guard/perf.h"

namespace mindspore {
namespace pijit {

class PerfStatisticsImpl : public PerfStatistics {
 public:
  PerfStatisticsImpl() = default;
  virtual ~PerfStatisticsImpl() = default;
  virtual double GetAverageDuration() { return avg_duration_; }
  virtual double GetMaxDuration() { return max_duration_; }
  virtual double GetMinDuration() { return min_duration_; }
  virtual int GetTotalCount() { return total_count_; }

 protected:
  friend class OptPerf;
  double avg_duration_ = 0.f;
  double max_duration_ = std::numeric_limits<double>::min();
  double min_duration_ = std::numeric_limits<double>::max();
  int total_count_ = 0;
};

OptPerf::OptPerf() : stat_(std::make_shared<PerfStatisticsImpl>()) {}

void OptPerf::AddDuration(double duration) {
  PerfStatisticsImpl *stat = static_cast<PerfStatisticsImpl *>(stat_.get());
  if (stat->max_duration_ < duration) {
    stat->max_duration_ = duration;
  }
  if (stat->min_duration_ > duration) {
    stat->min_duration_ = duration;
  }
  stat->avg_duration_ =
    (stat->avg_duration_ * stat->total_count_ + duration) / static_cast<double>(stat->total_count_ + 1);
  stat->total_count_ += 1;
}

PerfStatisticsPtr OptPerf::GetStatistics() { return stat_; }

}  // namespace pijit
}  // namespace mindspore
